gpt4 book ai didi

node.js - promise 未按正确顺序运行

转载 作者:搜寻专家 更新时间:2023-11-01 00:41:51 25 4
gpt4 key购买 nike

以下按顺序登录:here1 here2 here5 here3 here4。虽然,here5 应该是最后一个,它根本不会到达 here6。我怎样才能让 here1 到 here6 都按顺序正常运行?我正在使用 Sailsjs 和 Bluebird 。

//manually wrapping a callback API like Kaiseki
function createKaisekiObject(className, job) {
console.log('here2');
return new Promise(function(resolve, reject) {
kaiseki.createObject(className, job, function(err, res, body, success) {
//resolve or reject the promise
if (err) {
reject(err);
return;
}
console.log('here3');
resolve(body);
});
});
}

function saveJob(body) {
console.log('here4', body);

return Jobs.create({
owner: req.user.id,
jobId: body.objectId
});
}

function sendResponse(req, res) {
console.log('here5');

return function(savedJob) {
console.log('here6', savedJob, req, res);

// res.json({
// success: true,
// message: "Running analysis on game",
// jobId: savedJob.jobId
// });
//return the job
return savedJob;
};
}

module.exports.index = function(req, res) {
console.log('here1');
var jobId = uuid.v4();
var job = {
owner: req.user.id,
numOfGames: 1,
numOfGamesCompleted: 0
};
var className = 'jobs';
//promise
var createJob = createKaisekiObject(className, job)
.then(saveJob)
.then(sendResponse(req, res));

//when first step is done, do more stuff...
createJob.then(function(savedJob) {
//do more stuff here...
console.log('here6');
});


};

最佳答案

首先,我不相信 Jobs.create 会返回一个 promise ,因此如果您想继续链接,则需要将其包装在一个 promise 中。

function saveJob(body) {
console.log('here4', body);

return function(body) {
return new Promise(function(resolve, reject) {
Jobs.create({
owner: req.user.id,
jobId: body.objectId
}).exec(function(err, job) {
resolve(job);
});
});
};
}

接下来确保 sendResponse 返回的函数也返回一个 promise ,因为返回的函数将在链接的 then block 中执行。

function sendResponse(req, res) {
console.log('here5');

return function(savedJob) {
return new Promise(function(resolve, reject) {
console.log('here6', savedJob, req, res);
res.json({
success: true,
message: "Running analysis on game",
jobId: savedJob.jobId
});
//return the job
resolve(savedJob);
});
};
}

关于node.js - promise 未按正确顺序运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31396751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com