gpt4 book ai didi

Javascript 从嵌套函数返回值

转载 作者:太空宇宙 更新时间:2023-11-04 03:08:47 25 4
gpt4 key购买 nike

假设我有这个功能:

rest = require('restler');

function authenticate(credentials) {
var accessToken;

rest.post(BaseURL + '/Users/login', { data : credentials })
.on('complete', function(result, response) {
console.log(result.id); // this works fine
accessToken = result.id;
});

return accessToken;
};

我希望它返回 string包含accessToken 当我运行这个时:

var at = authenticate({ "username": "test", "password" : "test" });
console.log('Access Token:', at);

我得到Access Token : underfined

最佳答案

标准的、可接受的方法是修改authenticate函数:

function authenticate(credentials, cb) {
rest.post(BaseURL + '/Users/login', { data : credentials })
.on('complete', function(result, response) {
console.log(result.id); // this works fine
if (cb) { cb(result.id); }
}
});
};

然后像这样执行:

authenticate({ "username": "test", "password" : "test" }, function(at) {
console.log(at);
});

异步调用必须使用回调或 promise 来处理。 Promise 很“漂亮”,但只不过是回调而已。这就是为什么您会看到几乎每个 Node API 都利用回调。

关于Javascript 从嵌套函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31151292/

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