简体   繁体   English

节点Async / Await / Promise.All不等待其他人完成

[英]Node Async/Await/Promise.All not waiting for other to complete

I have 3 functions which I need to run in order and one needs to finish before the other runs so I've done this: 我有3个功能需要按顺序运行,一个功能需要在其他功能运行之前完成,所以我做到了:

var fs = require('fs');

async function create() {

    fs.writeFile('newfile.txt', 'some text here', (err) => {
        if (err) throw err;
        console.log('File is created successfully.');
        return ('File is created successfully.');
    }); 

}

async function waitt() {
    setTimeout(() => { return 'waited!' }, 10000);
}

async function read() {

    fs.readFile('newfile.txt', {encoding: 'utf-8'}, (err,data) => {
        if (!err) {
            console.log('received data: ' + data);
            return ('received data: ' + data);
        } else {
            console.log(err);
        }
    });

}

async function process() {

    let [r1, r2, r3] = await Promise.all([create(), waitt(), read()]);

    console.log(r1 + ' ' + r2 + ' ' + r3);

}


process();

So, process() runs create() which creates a file, then run waitt() which just pauses and finally read() shows the contents of the file. 因此,process()运行create()创建一个文件,然后运行waitt()只是暂停,最后read()显示该文件的内容。

The issue I'm having is that it's running in this order: 我遇到的问题是它按此顺序运行:

create()
read()
and then waitt()

instead of 代替

create()
waitt()
read()

which is what I want. 这就是我想要的。

How can I fix this? 我怎样才能解决这个问题?

This won't work: 这行不通:

async function waitt() {
  setTimeout(() => { return 'waited!' }, 10000);
}

Because, you're return -ing from within the setTimeout callback, not the async -marked wait function. 因为,您从setTimeout回调中return -ing,而不是从async标记的wait函数中返回。

To mix callback-style code and async/await you must first convert callback style code to use Promises , or use fs-extra which already provides fs functions returning promises. 要混合使用回调风格的代码和异步/等待,您必须先将回调风格的代码转换为Promises ,或者使用fs-extra ,它已经提供了返回承诺的fs函数。

Something like this: 像这样:

function waitt() {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve('waited...')
    }, 10000)
  })
}

The same applies to the rest of your functions. 其余功能也是如此。

Also note that if a function explicitly returns a Promise, it doesn't need to be marked as async to be awaited, since await essentially works with Promises. 还要注意,如果函数显式返回Promise,则不需要将其标记为async即可等待,因为await本质上与Promises一起使用。

Now for the order: 现在开始订购:

Promise.all doesn't guarantee order, for that you might be able to get away with a simple for..of , or just call the functions yourself. Promise.all不保证顺序,因为您可能可以使用简单的for..of摆脱困境 ,或者仅自己调用函数。

 function wait() { return new Promise((resolve, reject) => { setTimeout(() => { console.log('waited...') resolve('foo') }, 500) }) } // Assume this is your promisified read function. function read() { return new Promise((resolve, reject) => { setTimeout(() => { console.log('read...') resolve('bar') }, 500) }) } // Assume this is your promisified create function. function create() { return new Promise((resolve, reject) => { setTimeout(() => { console.log('created...') resolve('baz') }, 500) }) } ;(async () => { try { await create() await wait() await read() } catch (err) { console.error(err) } })() 

Your problem is that Promise.all does not guarantee the order of processing, just that all the promises in the list are processed. 您的问题是Promise.all不保证处理顺序,仅保证列表中的所有Promise都已处理。

Can you not just say: 你能不能只是说:

await create();
await read();
await waitt();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM