简体   繁体   English

Javascript:在嵌套函数中返回promise

[英]Javascript: Return promise in nested function

I have this code: 我有这个代码:

createOrUpdate({
    test: 'test'
}).then((response) => {
    console.log(response);
});

which will expect a createOrUpdate to return a promise. 期望createOrUpdate返回一个promise。 Here is the createOrUpdate function: 这是createOrUpdate函数:

function createOrUpdate(requestParams) {

    var options = {};

    return getService('global', function(error, serviceResult) {
        if (error) {
            log.error(error);
            return callback(error, null);
        }

        //...

        return requestPromise(options);
    });

}

I have this getService method that takes some paramaters and a call back. 我有这个getService方法,需要一些参数和一个回调。 I need to get that return requestPromise(options) to return when createOrUpdate is called, but currently it is not working. 我需要获取return requestPromise(options)以在调用createOrUpdate时返回,但是当前它不起作用。 I get an error saying I cannot call then on what createOrUpdate returns. 我收到一个错误,说我无法调用createOrUpdate返回的内容。

Ideas? 想法?

Simple, you need to make getService into a promise returning API . 很简单,您需要将getService变为promise返回API

Otherwise, node-callback taking functions don't return anything and ignore their own return values. 否则,节点回调函数不会return任何内容并忽略它们自己的返回值。

function createOrUpdate(requestParams) {

    var options = {};

    return fromCallback(getService)('global').then(options => 
        requestPromise(options);
    );

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM