gpt4 book ai didi

javascript - 函数返回未定义的、预期的 Promise 或值,而我返回新的 Promise

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:21 26 4
gpt4 key购买 nike

为什么我收到“函数返回未定义,预期的 promise 或值”?我无法理解。也许我错过了一些东西。

function getImage(url) {
console.log('Begin get image');
return new Promise(function(resolve, reject) {
https.get(url, res => {
// Initialise an array
const bufs = [];

// Add the data to the buffer collection
res.on('data', function (chunk) {
console.log('on data image');
bufs.push(chunk)
});

// This signifies the end of a request
res.on('end', function () {
console.log('on end image');

// We can join all of the 'chunks' of the image together
const data = Buffer.concat(bufs);

resolve(data);
});
})
// Inform the callback of the error.
.on('error', function (error) {
reject(error);
});
});
}

这是我调用该函数的地方:

getImage(imageURL)
.then( dataImg => {
console.log('image get get');
(...)
}

我应该获取 dataImg 并进行操作。

最佳答案

我使用 Node 测试了以下代码并收到了图像缓冲区。也许检查一下您是否在某处遗漏了一些括号。

var https = require("https");

function getImage(url) {
console.log('Begin get image');

// Return the loading-promise
return (new Promise((resolve, reject) => {
https.get(url, (res) => {
// Initialise an array to store the image-data
const bufs = [];

// Add the data to the buffer collection
res.on('data', function(chunk) {
console.log('on data image');
// Push the recieved chunks into the array
bufs.push(chunk)
});

// This signifies the end of a request
res.on('end', function() {
console.log('on end image');

// We can join all of the 'chunks' of the image together
const data = Buffer.concat(bufs);

// Return the image-buffer
resolve(data);
});
})
// Inform the callback of the error.
.on('error', function(error) {
reject(error);
});
}));
}

(function() {
getImage("https://preview.redd.it/utrlx02sx2431.jpg?width=640&crop=smart&auto=webp&s=8ed20013607e0d6019f59ab01b0e4930eb913351")
.then((dataImg) => {
console.log('image get get');
console.log(dataImg);
});
})();

控制台输出:

ab@xy:~/test$ node testrun.js 
Begin get image
on data image
on data image
on end image
image get get
<Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 01 01 00 00 00 00 00 00 ff e1 00 42 45 78 69 66 00 00 4d 4d 00 2a 00 00 00 08 00 01 87 69 00 04 00 00 00 01 00 00 ... 20311 more bytes>

关于javascript - 函数返回未定义的、预期的 Promise 或值,而我返回新的 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56579965/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com