thunk,期货和承诺有什么区别?

JRR*_*JRR 30 future delayed-execution thunk promise

有关于它们的维基文章:(http://en.wikipedia.org/wiki/Futures_and_promises,http://en.wikipedia.org/wiki/Thunk_ ( delayed_computation)).但我不确定三者作为编程语言概念之间的确切差异是什么?期货和承诺只适用于并发编程吗?

slf*_*slf 16

每个人的一个例子,使用javascript,因为每个人都可以阅读它.

请不要在生产中使用此代码,使用真正的库,有很多好的.

var a, b, c, async_obj;  // assume exist

// CommonJS - for reference purposes

try {

  async_obj.asyncMethod(a, b, c, function (error1, result1) {

    if (error1) {
      console.error(error1);
    } else {
      console.log(result1);
    }

  });

} catch (ex1) {
  console.error(ex1);
}

// Thunk - "a parameterless closure created to prevent the evaluation of an expression until forced at a later time"

function makeThunkForAsyncMethod (cb) {
  return function () {
    async_obj.asyncMethod(a, b, c, cb);
  }
}

var my_thunk = makeThunkForAsyncMethod(function (error1, result1) {
  if (error1) {
    console.error(error1);
  } else {
    console.log(result1);
  }
});

setTimeout(function () {
  try {
    my_thunk();
  } catch (ex1) {
    console.error(ex1);
  }
}, 5e3);


// Promise - "a writable, single assignment container which sets the value of the future"

function makePromiseForAsyncMethod () {
  var
    future_then_cb,
    future_catch_cb,
    future
  ;

  future = {
    then: function (cb) {
      future_then_cb = cb;
    },
    catch: function (cb) {
      future_catch_cb = cb;
    };
  };

  try {
    async_obj.asyncMethod(a, b, c, function (error1, result1) {
      if (error1) {
        if (future_catch_cb) {
          future_catch_cb(error1)
        }
      } else {
        if (future_then_cb) {
          future_then_cb(result1);
        }
      }
    });
  } catch (ex1) {
    setTimeout(function () {
      if (future_catch_cb) {
        future_catch_cb(ex1);
      }
    });
  }

  return future;
}

// Future - "a read-only placeholder view of a variable"

var my_future = makePromiseForAsyncMethod();

my_future
  .then(function (result) {
    console.log(result);
  })
  .catch(function (error) {
    console.error(error);
  })
;
Run Code Online (Sandbox Code Playgroud)

Promise链就像上面提到的例子一样,但它可以用于集合并且更加健壮.

  • 代码确实解释了很多,但是如果你能添加更多解释就更好了。 (2认同)

Sea*_*ean 13

在功能编程,之间的最差thunkpromise是,thunk是纯而promise不纯.

function thunkDemo() {
  return function(callback) {
    asyncMethod(someParameter, callback);
  };
}

function promiseDemo() {
  return new Promise(function(resolve, reject) {
     asyncMethod(someParameter, function(err, data) {
        if(err) return reject(err);
        resolve(data);
     });
  });
}
Run Code Online (Sandbox Code Playgroud)

thunkDemo被调用时,asyncMethod将不被调用,直到称为内的方法,因此是thunkDemo纯,无副作用的影响.

promiseDemo被调用时,它会立即调用asyncMethod,这意味着它不是纯粹的.