2017-10-20 104 views
0

我設法讓我的代碼等待提示,但由於某種原因它不會在收到提示後繼續。輸出是:與提示的木偶,忽略功能的其餘部分

prompt: password: 
Command-line input received: 
    password: password 

下面的代碼:

const puppeteer = require('puppeteer'); 
const prompt = require('prompt'); 
const url = 'some url'; 

var schema = { 
    properties: { 
    password: { 
     hidden: true 
    } 
    } 
}; 

prompt.start(); 

(async() => { 
    var result = await new Promise(function (resolve, reject) { 
     return prompt.get(schema, function (err, result) { 
      console.log('Command-line input received:'); 
      console.log(' password: ' + result.password); 
      return result; 
     }) 
    }); 
    console.log(result); 
    const browser = await puppeteer.launch({ headless: false }); 
    const page = await browser.newPage(); 
    await page.goto(url); 
    /* truncated */ 
})(); 

回答

1

你必須解決的承諾。我重新編寫了一些代碼,以便在實踐中展示這個概念。

const puppeteer = require('puppeteer'); 
const prompt = require('prompt'); 

var schema = { 
    properties: { 
     url: { 
      hidden: false 
     } 
    } 
}; 

prompt.start(); 

(async() => { 
    var result = await new Promise(function (resolve, reject) { 
     prompt.get(schema, function (err, result) { 
      resolve(result); 
     }); 
    }); 
    const browser = await puppeteer.launch({ 
     headless: true 
    }); 

    const page = await browser.newPage(); 
    await page.goto(result.url); 
    const title = await page.title(); 

    console.log(`${result.url} has title: ${title}`); 

    await page.close(); 
    await browser.close(); 
    /* truncated */ 
})(); 

並運行它將產生以下結果。

▶ node prompt.js 
prompt: url: http://example.com 
http://example.com has title: Example Domain 

▶ node prompt.js 
prompt: url: http://google.com 
http://google.com has title: Google 

祝您好運。

+0

我會在訪問代碼時回覆您 –