在 javascript 中使用替换方法时 Promise 返回 [object Promise]

问题描述 投票:0回答:1

我尝试了下面的代码,其中发生了内部替换方法 fetch api 调用,并且它返回响应并基于返回的响应

<img>
。但问题是它返回 [object Promise]

 .replace(/!([^|!]*(?:jpe?g|png|gif|mp4|mp3|mkv|mov))(?:\|width=(\d*\.?\d+%?)(?:,height=(\d*\.?\d+%?))?)?!/gm,  async (match, capture) => {
                let m, reg = /!([^|!]*(?:jpe?g|png|gif|mp4|mp3|mkv|mov))(?:\|width=(\d*\.?\d+%?)(?:,height=(\d*\.?\d+%?))?)?!/gm;
                let imageConfig = [];
                while ((m = reg.exec(str)) !== null) {
                    imageConfig.push({ file: m[1], width: (m[2] || ''), height: (m[3] || '') });
                }
                let payload = {
                    'columns': [
                        {
                            'id': columnMeta.id,
                            'values': [
                                { "type": "@thumbnail", "values": imageConfig.map(e => e?.file) },
                            ]
                        }
                    ]
                }
                payload.rowId = rowData?.id;
                let reolvedFile = [];
                let response = await Service.post(
                    generateAPIURL({
                        boardId: TableHelper.getwrapperConfig?.boardId,
                        tableId: TableHelper.getwrapperConfig?.tableId,
                        columnId: columnMeta?.id,
                        type: "getresolvedValue",
                    }),
                    null,
                    JSON.stringify({ ...payload })
                )
                let values = response?.columns?.[0]?.values;
                imageConfig.map(e => e?.file)?.map(o => {
                    let index = values?.findIndex(e => e?.name === o);
                    if (index !== -1) {
                        reolvedFile.push(values[index]);
                    }
                })
                
                //Find the matching entry
                var info = reolvedFile?.find(({ name }) => name === capture);
                let width = imageConfig.find((e) => e?.file === capture)?.width || 200;
                let height = imageConfig.find((e) => e?.file === capture)?.height || 200;
                return info ?
                    `<img src="${info?.thumbnail}"   data-name="${info?.name}"  width=${width} height=${height} style="width:'${width}px';height:'${height}px';display: inline-block;"/>`
                    : `<div  id="${capture}" data-name="${capture}" class="linear-background" style="width:'${width}px';height:'${height}px';display: inline-block;" ></div>`;
            })

我尝试了上面的代码,并期望它应该在响应到来后返回

<img>
而不是[object Promise]

`return info ?
                `<img src="${info?.thumbnail}"   data-name="${info?.name}"  width=${width} height=${height} style="width:'${width}px';height:'${height}px';display: inline-block;"/>`
                : `<div  id="${capture}" data-name="${capture}" class="linear-background" style="width:'${width}px';height:'${height}px';display: inline-block;" ></div>`;
        })``
javascript
1个回答
0
投票

String#replace
没有规定等待替换函数返回的 Promise 完成 - 并且您正在返回一个 Promise,因为替换器是
async

你需要一些可以处理这个问题的东西,例如

async function asyncStringReplace(string, pattern, replacer) {
  
  const promises = [];
  // Find all replacements once (discarding the result),
  // but keeping track of the promises that will eventually
  // resolve to the replacement values
  string.replace(pattern, (match, ...args) => {
    promises.push(replacer(match, ...args));
  });
  // Await for all of the gathered promises to resolve
  const replacements = await Promise.all(promises);
  // Run the replacement again, draining the replacements array
  return string.replace(pattern, () => replacements.shift());
}

async function fetchResultForMatch(m) {
  // pretend we'd fetch something from the network
  return m.toUpperCase() + "!";
}

async function main() {
  const string = "hello world, all words longer than five letters in this text should be screamy";
  const result = await asyncStringReplace(string, /\w{5,}/g, fetchResultForMatch);
  console.log(result);
}

main();

© www.soinside.com 2019 - 2024. All rights reserved.