Cloudinary API-解决承诺 [英] Cloudinary api - resolve promise

查看:56
本文介绍了Cloudinary API-解决承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个函数,该函数返回一个布尔值,该值指示在我的Cloudinary空间中是否已经存在具有指定public_id的图像.

I want to write a function that returns a Boolean indicating whether an image with the specified public_id already exists in my Cloudinary space.

我可以使用以下代码将结果记录到控制台:

I can log the result to the console with the following code:

function isUploaded(public_id) {
  cloudinary.api.resource(public_id, function(response){
    console.log(response.hasOwnProperty('public_id'));
  });
};

isUploaded('test');

但是,我想将结果布尔值传递给另一个函数.使用return语句会导致记录 {状态:'pending'} :

However, I want to pass on the result, the Boolean, to another function. Using a return statement results in { state: 'pending' } being logged:

function isUploaded(public_id) {
  return cloudinary.api.resource(public_id, function(response){
    return response.hasOwnProperty('public_id');
  });
};

console.log(isUploaded('test'));

这与javascript Promises有关.我似乎无法重组我的代码以使其正常运行.任何帮助将不胜感激.

This is has something to do with javascript Promises. I can't seem to restructure my code to make it work though. Any help would be much appreciated.

推荐答案

问题是 cloudinary.api.resource 异步运行(这就是为什么需要回调函数的原因).

The problem is that cloudinary.api.resource runs asynchronously (which is why it requires a callback function).

您可以使您的 isUploaded 函数返回一个 Promise ,一旦回调被调用,它便会解决.

You can make your isUploaded function return a Promise that resolves once that callback is called.

var cloudinary = require('cloudinary');

function isUploaded(public_id) {
  return new Promise(function (resolve, reject) {
    cloudinary.api.resource(public_id, function(response) {
      var isUploaded = response.hasOwnProperty('public_id');
      resolve(isUploaded);
    });
  });
};

isUploaded('test')
.then(function (result) {
  console.log(result);
})

这篇关于Cloudinary API-解决承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆