最后一个关于回调函数的问题

One last question concerning callback functions

const geocode = (address, callback) => {
  const url = `https://api.mapbox.com/geocoding/v5/mapbox.places/${address}.json?access_token=pk.eyJ1IjoibWVya3VyMTIzIiwiYSI6ImNrYjVndDk3bjBvNGEyeW16cHlid2txZ3YifQ.NGOWOq0yq0wvkhzDzjnUpQ&limit=1`;
  request({ url, json: true }, (error, response) => {
    const data = response.body;
    if (error) {
      callback('Unable to connect to the Geo API', null);
    } else if (data.message === 'Not Found' || data.features.length === 0) {
      callback('Location not found', null);
    } else {
      callback(null, {
        longitude: data.features[0].center[0],
        latitude: data.features[0].center[1],
        location: data.features[0].place_name,
      });
    }
  });
};

大家好,我有最后一个关于回调函数的问题。在上面的代码中,回调函数在 web API 完成后立即被调用,但为什么它起作用而不是 return 语句而不是回调函数,如:

return {
        longitude: data.features[0].center[0],
        latitude: data.features[0].center[1],
        location: data.features[0].place_name,
      }

那么为什么回调函数只在WEB API 完成时调用,而return 函数立即被调用因此不起作用,但实际上为什么? return 不也是一个函数吗?

主要问题是它应该return到哪里?。在您的情况下,您处于一个回调中,该回调由 request 的内部逻辑调用,因此您可以 return 该逻辑(但这将毫无用处)。函数始终同步运行,这也意味着您必须同步 return。函数执行完毕后不能return:

 function synchronous(asynchronous) {
    setTimeout(function callback () {
       var value = asynchronous(); // This is the place were the value ends up ...
    }, 1000);
    return; // however we can't return value here as this part executed long before
 }

 synchronous(function callback2() {
   return "test"; // this will end up in 'value'
 });

代码基本上有以下任务和调用栈:

 task: synchronous execution
   -> synchronous() -> setTimeout()
   <-               <-               // this is the place you want to return to   

 task: timer done
   -> callback() -> callback2()
   <-            <-              // this is the place were you actually return