我正在完全重写我的问题,请将其进一步简化。
在下面的代码中,为什么x()等同于undefined,而不是console.log('success');记录到控制台的success
最后一行在控制台中执行完毕;然后触发.then()回调。
如何才能使x()在最后一行开始执行之前返回'success‘值。
甚至yF()的计算结果也是undefined。但是,.then()正在响应th y: success。
const promise = require('promise');
const requestify = require('requestify');
function x() {
requestify.get('https://<redacted>/')
.then(function (d) {
console.log('success', d.code);
return 'success';
})
.fail(function (f) {
console.log('fail', f.code);
return 'fail';
});
;
}
var yF = function () {
yP .then(function (th) { console.log("th", th); return th; })
.catch(function (fl) { console.log("fl", fl); return fl; });
}
var yP = new Promise(
function (resolve, reject) {
if (1 == 1) {
resolve("y: success");
} else {
reject(new Error("y: fail"));
}
}
);
console.log("hello", x());
console.log("world", yF());发布于 2017-07-02 05:33:14
函数x不返回值。此示例可能会有所帮助:
> function foo() { console.log('hi from foo'); }
undefined
> console.log('calling foo', foo());
hi from foo
calling foo undefined您需要在函数中返回promise。函数x可能会发生如下变化:
function x() {
return requestify.get('https://<redacted>/')
.then(function (d) {
console.log('success', d.code);
return 'success';
})
.fail(function (f) {
console.log('fail', f.code);
return 'fail';
});
}现在可以用then调用x了
x().then(result => assert(result === 'success'));发布于 2017-07-02 07:05:05
两种方法:
1) x() ~我会调用,向前传递一个变量
2) yP()~消费承诺
const promise = require('promise');
const requestify = require('requestify');
var f = "";
function yP() {
return new Promise(function (resolve, reject) {
requestify.get('https://<redacted>')
.then(function (da) {
var fpt = "success(yP):" + da.code.toString();
console.log('success-yP', fpt);
resolve(fpt);
})
.catch(function (ca) {
var fpc = "fail(yP):" + ca.code.toString();
console.log('fail-yP', fpc);
reject(fpc);
});
});
}
function x() {
requestify.get('https://<redacted>/')
.then(function (da) {
f = "success(x):" + da.code.toString();
console.log('success-x', f);
consumef();
})
.catch(function (ca) {
f = "fail(x):" + ca.code.toString();
console.log('fail-x', ca);
consumef();
});
;
}
function consumef() {
console.log("hello", f);
}
x();
yP()
.then(function (fyPt) { console.log('yP().then', fyPt); })
.catch(function (fyPc) { console.log('yP().catch', fyPc); });调试器侦听:5858
成功-yP成功(YP):200
yP().then成功(YP):200
成功-x成功(X):200
hello success(x):200
https://stackoverflow.com/questions/44862450
复制相似问题