Promise.then()但函数运行异步

时间:2016-10-14 11:28:53

标签: javascript node.js promise

我是Javascript的新手并且正在使用抓取工具,我已经创建了4个Promise,因为这些

var openConfig = new Promise((resolve, reject) => {
  fs.readFile('./config.json', (err, data) => {
    if (err) throw err;
    config = JSON.parse(data);
    client = new MsTranslator({
      client_id: config.translatorId,
      client_secret: config.translatorSecret
    }, true)
    resolve();
  })
})

var openFile = new Promise((resolve, reject) => {
  console.log('Opening file...')
  fs.readFile('./writing/writing.json', (err, data) => {
    if (err) throw err;
    writing = JSON.parse(data);
    console.log('Done parsing file');
    resolve();
  })
})

var ask = new Promise((resolve, reject) => {
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  })
  rl.question('Which lesson do you want to add? ', (ans) => {
    lessonId = ans;
    rl.close();
    resolve();
  })
})

var createLesson = new Promise((resolve, reject) => {
  console.log('Now processing lesson ' + lessonId);
})

然后调用第一个Promise

openConfig
  .then(() => {
    return openFile;
  })
  .then(() => {
    return ask;
  })
  .then(() => {
    return createLesson;
  })

但是当我跑步时,控制台显示

Opening file...
Which lesson do you want to add? Now processing lesson undefined
Done parsing file

我理解为我的承诺是错误的,我的函数运行异步。你能帮我解决这个问题吗?

谢谢。

2 个答案:

答案 0 :(得分:2)

承诺不是“被称为”。在then链中,您只是顺序等待它们 - 但是当您创建承诺时,任务已经开始了。如果要对操作进行排序,请将它们放在函数中。

顺便说一句,您的代码包含多个典型错误。 Don't use global variables,并始终promisify处于最低级别:

function openFile(path) {
  return new Promise((resolve, reject) => {
    fs.readFile('./config.json', (err, data) => {
      if (err) reject(err); // never `throw err` in non-promise callbacks!
      else resolve(data);
    });
  });
}
function openJSON(path) {
  return openFile(path).then(JSON.parse);
}
function openConfig(path) {
  return openJSON(path).then(config =>
    new MsTranslator({
      client_id: config.translatorId,
      client_secret: config.translatorSecret
    }, true)
  )
}
function ask(question) {
  return new Promise((resolve, reject) => {
    var rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    })
    rl.question(question, ans => {
      rl.close();
      resolve(ans); // always resolve to *something*
    });
  });
}

readConfig('./config.json')
.then(client => {
  console.log('Opening file...')
  return openJSON('./writing/writing.json');
})
.then(writing => {
  console.log('Done parsing file');
  return ask('Which lesson do you want to add? ');
})
.then(lessonId => {
  console.log('Now processing lesson ' + lessonId);
});

答案 1 :(得分:0)

不是将新的Promises分配给变量(这些变量在创建后立即运行),而是应该将它们包装到函数中,然后函数返回一个新的Promise

为了帮助您理解这里的简化示例:

function p1 (data) {
    return new Promise(function (resolve, reject) {
        resolve(Object.assign(data, {a:1}));
    });
}

function p2 (data) {
    return new Promise(function (resolve, reject) {
        resolve(Object.assign(data, {b:2}));
    });
}

function p3 (data) {
    return new Promise(function (resolve, reject) {
        resolve(Object.assign(data, {c:3}));
    });
}

p1({z:0})
.then(p2)
.then(p3)
.then((data)=>console.log(data))

这导致{ z: 0, a: 1, b: 2, c: 3 }

如果您想对上述内容进行一些实验,请参阅此处:https://repl.it/DwNB/0

另外,如果您使用的是promises,则还应该在最终.catch()中处理链中的错误,而不是在中途同步throw。这就是reject回调的用途!