You want the callback to be executed after findById, but it cannot be placed in its callback, otherwise it will be executed multiple times. What should I do?
Software is a service industry, you must have service awareness... There is no problem with the code map, you can see it very clearly, but if the respondent wants to change your code, you have to type it again...
I see that you have already used es6 syntax, so the correct solution must be Promise, which can be encapsulated into Promies by yourself
Of course, you can also use the tool functions provided by Bluebird to encapsulate Promise
It should be noted that you are running multiple asynchronous calls here, so if you want to return them together, there must be multiple results. So notice the callback in Promise.all 后面 then().
If you want to use es5, it is recommended that you write es6 and then use Babel. However, Node 7.6+ already supports some features of es2017, so you don’t actually need to worry about this issue. If you really need it, use the method of counting in the findById callback to count up the enlargement moves (call the callback).
I see that you have already used es6 syntax, so the correct solution must be Promise, which can be encapsulated into Promies by yourself
Of course, you can also use the tool functions provided by Bluebird to encapsulate Promise
It should be noted that you are running multiple asynchronous calls here, so if you want to return them together, there must be multiple results. So notice the callback in
Promise.all
后面then()
.If you want to use es5, it is recommended that you write es6 and then use Babel. However, Node 7.6+ already supports some features of es2017, so you don’t actually need to worry about this issue. If you really need it, use the method of counting in the
findById
callback to count up the enlargement moves (call the callback).Option 1
Use
async/await
。这样就可以按照同步方式使用User.findById
.Option 2
Insert
User.findById
加入一个数组,然后用Promise.all
,callback
写在Promise.all().then()
in the loop.Option 3
Use a state variable, check it every time, and then execute it if the conditions are met
callback
. Ugly method, don't use it.Set a parameter, execute the setting, and then enter the callback judgment every time..
For callback hell, please use Promise or similar libraries.
My solution is a bit low. . ?
The second floor is right, use promise to solve it.