gpt4 book ai didi

javascript - 控制回调流程

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

我有以下 Node.js 代码。

index.js

"use strict";
// Close dialog with the user, reporting fulfillmentState of Failed or Fulfilled

var service = require("./service.js");

function dispatch() {
const op = service.createIncident("enterpriseID", "shortDesc", function(
incidentNo
) {
if (incidentNo) {
console.log("Index.js ServiceNow Incident:" + incidentNo);
var msg = "Thank you! Your Number is " + incidentNo;
console.log("end of flow");
} else {
console.log("Index.js ServiceNow Incident:" + incidentNo);
msg = "Err";
console.log("end of flow");
}
});
console.log("done");
}

dispatch();

这是我的 service.js

var request = require("request-promise");
var servicenow = require("./configfile.json");

var snowURL = servicenow.url;
var snowUsername = servicenow.username;
var snowPassword = servicenow.password;
var ticketNo = "00000";

console.log(
"Service Now URL:" +
snowURL +
" Username:" +
snowUsername +
" Password:" +
snowPassword
);

module.exports = {
createIncident: function(caller_id, short_description, callback) {
var snowdetails = {
uri: snowURL,
json: {
short_description: short_description
},
method: "POST",
auth: {
username: snowUsername,
password: snowPassword
}
};

request(snowdetails)
.then(function(body) {
var data = JSON.parse(JSON.stringify(body));
ticketNo = data.result.number;
console.log("Service Now Incident No:" + ticketNo);
callback(ticketNo);
})
.catch(function(err) {
console.log(err);
});
}
};

当我运行这个程序时,我得到的输出是

Service Now URL:myUrl 
Username:myUserName Password:myPassword
done
Service Now Incident No:INC0010107
Index.js ServiceNow Incident:INC0010107
end of flow

但根据流程,我需要输出为。

Service Now URL:myUrl
Username:myUserName Password:myPassword
Service Now Incident No:INC0010107
Index.js ServiceNow Incident:INC0010107
end of flow
done

我知道这与回调和 promise 有关,但不知道如何做。请帮助我了解我应该更改什么以获得流程中的输出(done 作为最后一件事打印)

最佳答案

打印 done 的控制台语句不在回调中,因此在调用 service.createIncident 后立即执行。

很容易修复,只需将日志语句移到回调中即可:

function dispatch() {
const op = service.createIncident("enterpriseID", "shortDesc",
function (incidentNo) {
if (incidentNo) {
console.log("Index.js ServiceNow Incident:" + incidentNo);
var msg = "Thank you! Your Number is " + incidentNo;
console.log("end of flow");
} else {
console.log("Index.js ServiceNow Incident:" + incidentNo);
msg = "Err";
console.log("end of flow");
}
console.log("done");
}
);
}

关于javascript - 控制回调流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45946176/

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