【问题标题】:node js call a promise function inside a chain .thennode js在链中调用promise函数.then
【发布时间】:2020-10-22 04:53:03
【问题描述】:

您好,我是异步调用的新手,希望您能帮助我。

我有一个 .then 链,我想在链的中间调用一个返回 promise 的函数,但我碰巧链没有等待它获得 promise 函数的结果并继续没有等待

var User = require('../models/user_model');
var mapbox = require('./helper/request_api_mapbox');

findOne_mapbox: (req, res) => {
  User.findById(req.params.id)
        .then(user => {
            
            ...
            return user.address;
        })
         .then(function (adress_to_mapbox) 
            {
                // mapbox.connect_mapbox returns a promise
                mapbox.connect_mapbox(adress_to_mapbox)
                .then(mapbox_coordinates => {
                    //inside this console.log is not read it
                    console.log("2 then mapbox_coordinates ", mapbox_coordinates)
                    return Promise.resolve(body);
                })   
                           
            })
             .then(  mapbox_coordinates  => {

                // in this console.log mapbox_coordinates returns undefined
                console.log("last promise mapbox_coordinates", 
                mapbox_coordinates)

                // I want to return mapbox_coordinates
                return res.status(200).send({
                    "response": "I only receive this string " 
                });
            })

}

promise 函数是:

'use strict'

const rp = require('request-promise');
const access_token_mapbox = 'bla bla bla private';

function connect_mapbox(adress_to_mapbox) {
    return new Promise((resolve, reject) => {  
        
        var options = {
            method: 'GET',
            uri: 'https://api.mapbox.com/geocoding/v5/mapbox.places/' + adress_to_mapbox + '.json?access_token=' + access_token_mapbox,                 
            json: true // Automatically stringifies the body to JSON
        };
    
        rp(options)
        .then(body => {
            if (body.hasOwnProperty('errcode') && body.errcode != 0) {
            return Promise.reject(body);
            }
            console.log("inside connect_mapbox function on mapbox_model 2", body)
            
            return Promise.resolve(body);
        })
        .catch(err => {
            debug(err);
            return Promise.reject(err);
        })
        
    })  
}   

module.exports = { connect_mapbox };

在我的console.log中可以看到promise函数内部,它可以正确调用api并且响应体是好的。

【问题讨论】:

    标签: node.js promise request-response


    【解决方案1】:

    我是从编程开始的,虽然不知道是不是最正确,但是我用下面的方法解决了这个问题

    我通过将 connect_mapbox 承诺函数转换为 async await 并将 .then 链转换为 async await 来解决它,如下所示:

    'use strict'
    
    const rp = require('request-promise');
    const access_token_mapbox = 'bla bla bla private';
    
    async function connect_mapbox(adress_to_mapbox) {
    
        try {
    
            var options = {
                method: 'GET',
                uri: 'https://api.mapbox.com/geocoding/v5/mapbox.places/' + adress_to_mapbox + '.json?access_token=' + access_token_mapbox,                 
                json: true // Automatically stringifies the body to JSON
            };
    
            let response = await rp(options);
    
            console.log("inside connect_mapbox function on mapbox_model", response)
    
            if (response.hasOwnProperty('errcode') && body.errcode != 0) {
                return Promise.reject(response);
            }
    
            return Promise.resolve(response);
    
        }catch(error) {
            return Promise.reject(error);
        }
    }
    
    module.exports = { connect_mapbox };
    

    还有 .then 类似的链

    var User = require('../models/user_model');
    var mapbox = require('./helper/request_api_mapbox');
    
    findOne_mapbox: (req, res) => {
      User.findById(req.params.id)
            .then(user => {
                
                ...
                return user.address;
            })
             .then(async function (adress_to_mapbox) 
                {
                    
                    console.log("adress_to_mapbox thit could be deleted", adress_to_mapbox)
                        
                    let mapbox_response = await mapbox.connect_mapbox(adress_to_mapbox)
                       
                    console.log("async mapbox_response", mapbox_response) 
    
                    return res.status(200).send({
                        mapbox_response 
                    });
                })
                 ...
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      • 2016-02-14
      • 1970-01-01
      • 2022-06-22
      • 2019-01-09
      相关资源
      最近更新 更多