我有一个由API PUT调用组成的函数。当我点击函数调用更新时,问题是首先返回函数,然后请求写入API,因为我将结果视为未定义。如何解决这个问题
//update function call
var result = update(object);
console.log('result ', result);
function update(obj){
var obj = obj;
var err = '';
var str = '';
var options = {
host: HOST,
port: PORT,
path: PATH + '/update/' + obj.id,
headers: { "content-type": "application/json" },
method: 'PUT'
};
try {
var request = http.request(options, function (response) {
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
util.log('\nsaved.' + str);
});
response.on('error', function (e) {
util.log('\nError while saving.' + e);
err = 'Something went wrong. Please try again later.';
});
});
var jsonObject = JSON.stringify(obj);
util.log('\n Sent to Update ' + jsonObject);
request.write(jsonObject);
request.on('error', function (e) {
util.log('\nError while updating request. ' + e);
err = 'Something went wrong. Please try again later.';
});
request.end('end', function(e){
util.log('On request end ' + str);
return (str || {err : err});
});
} catch (err) {
util.log("\nUpdating failed. " + err.stack);
return ({err: 'Failed to update. Please try again.'});
}
}
答案 0 :(得分:0)
首先你需要知道异步和非阻塞。当你的函数运行时,节点正在读取其他代码,当生成结果时它会返回值,但现在你的其他代码应该在控制台上显示你的答案了并将其打印为未定义。
您可以搜索节点和其他许多内容中的回调,首先您应该更好地了解您的工具:)
这是具有真实结构的代码:
update(object ,function(result){
console.log('result :', result);
});
function update(obj,callback){
...
// removed : return (str || {err : err});
callback (str || {err : err});
...
// removed : return ({err: 'Failed to update. Please try again.'});
callback ({err: 'Failed to update. Please try again.'});
}